package com.china08.yxyapi.api.comm;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.entity.db.res.YxyResResource;
import com.china08.yxyapi.entity.db.res.YxyResResource2;
import com.china08.yxyapi.entity.db.res.YxyResResourceBookContent;
import com.china08.yxyapi.entity.db.res.YxyResResourceForEsReindex;
import com.china08.yxyapi.entity.db.res.YxyResWeikeKnow;
import com.china08.yxyapi.entity.mg.lecture.YxyLecturePrePack;
import com.china08.yxyapi.entity.mg.lecture.YxyLecturePrePack.Res;
import com.china08.yxyapi.entity.mg.lecture.YxyLectureRes;
import com.china08.yxyapi.entity.mg.lecture.YxyLectureRes.Knows;
import com.china08.yxyapi.entity.mg.res.YxyResQues;
import com.china08.yxyapi.model.ResModel;
import com.china08.yxyapi.model.lecture.ReqLectureKnowModel;
import com.china08.yxyapi.model.lecture.ReqLecturePrePackModel;
import com.china08.yxyapi.model.lecture.ReqLecturePrePackResModel;
import com.china08.yxyapi.model.lecture.ReqLectureResKnowModel;
import com.china08.yxyapi.model.lecture.ReqLectureResModel;
import com.china08.yxyapi.model.lecture.ReqQuesModel;
import com.china08.yxyapi.model.lecture.ReqSynLectureModel;
import com.china08.yxyapi.repository.db.YxyResResourceBookContentRepository;
import com.china08.yxyapi.repository.db.YxyResResourceForEsReindexRepository;
import com.china08.yxyapi.repository.db.YxyResResourceRepository;
import com.china08.yxyapi.repository.db.YxyResResourceRepository2;
import com.china08.yxyapi.repository.db.YxyResWeikeKnowRepository;
import com.china08.yxyapi.repository.mg.YxyResQuesRepository;
import com.china08.yxyapi.repository.mg.lecture.YxyLecturePrePackRepository;
import com.china08.yxyapi.repository.mg.lecture.YxyLectureResRepository;

@CrossOrigin
@RestController
public class SynLectureController {

    @Autowired
    public YxyLecturePrePackRepository yxyLecturePrePackRepository;

    @Autowired
    private YxyResResourceRepository yxyResResourceRepository;

    @Autowired
    private YxyResResourceRepository2 yxyResResourceRepository2;

    @Autowired
    private YxyResResourceBookContentRepository yxyResResourceBookContentRepository;

    @Autowired
    private YxyResWeikeKnowRepository yxyResWeikeKnowRepository;

    @Autowired
    private YxyResQuesRepository yxyResQuesRepository;

    @Autowired
    private YxyResResourceForEsReindexRepository yxyResResourceForEsReindexRepository;

    @Autowired
    private YxyLectureResRepository yxyLectureResRepository;

    private static final Logger LOGGER = LoggerFactory.getLogger(SynLectureController.class);

    @PostMapping(value = "/api_yw/comm/sync/lecture")
    public ResModel find(HttpServletRequest request, HttpServletResponse response,
            @RequestBody ReqSynLectureModel reqModel) {
        LOGGER.info("同步备授课开始");
        ResModel resModel = new ResModel();
        try {
            List<YxyResResource> yxyResResources = reqModel.resources != null ? reqModel.resources : new ArrayList<>();
            if (yxyResResources.size() > 0) {
                List<YxyResResourceBookContent> resourceBookContents = reqModel.resourceBookContents != null
                        ? reqModel.resourceBookContents : new ArrayList<YxyResResourceBookContent>();
                List<YxyResWeikeKnow> weikeKnows = reqModel.weikeKnows != null ? reqModel.weikeKnows
                        : new ArrayList<YxyResWeikeKnow>();
                for (YxyResResource yxyResResource : yxyResResources) {
                    String resourceId = yxyResResource.getId();
                    Integer count = yxyResResourceRepository.countById(resourceId);
                    if (count == 0) {
                        YxyResResource2 resource2 = new YxyResResource2();
                        BeanUtils.copyProperties(yxyResResource, resource2);
                        yxyResResourceRepository2.save(resource2);
                    } else {
                        resourceBookContents.removeIf(x -> StringUtils.equals(x.getResourceId(), resourceId));
                        weikeKnows.removeIf(x -> StringUtils.equals(x.getWeikeId(), resourceId));
                    }
                }
                if (resourceBookContents.size() > 0) {
                    for (YxyResResourceBookContent rb : resourceBookContents) {
                        YxyResResourceBookContent bookContentRes = yxyResResourceBookContentRepository
                                .findByResourceIdAndBookContentId(rb.getResourceId(), rb.getBookContentId());
                        if (bookContentRes == null) {
                            yxyResResourceBookContentRepository.save(rb);
                        }
                    }
                    List<String> resourceIds = resourceBookContents.stream().map(x -> x.getResourceId())
                            .collect(Collectors.toList());
                    for (String string : resourceIds) {
                        YxyResResourceForEsReindex esReindex = new YxyResResourceForEsReindex();
                        esReindex.setResourceId(string);
                        yxyResResourceForEsReindexRepository.save(esReindex);
                    }
                }
                if (weikeKnows.size() > 0) {
                    for (YxyResWeikeKnow rw : weikeKnows) {
                        YxyResWeikeKnow knowThreeId = yxyResWeikeKnowRepository.findByWeikeIdAndKnowId(rw.getWeikeId(),
                                rw.getKnowId());
                        if (knowThreeId == null) {
                            yxyResWeikeKnowRepository.save(knowThreeId);
                        }
                    }
                    List<String> weikeIds = weikeKnows.stream().map(x -> x.getWeikeId()).collect(Collectors.toList());
                    for (String string : weikeIds) {
                        YxyResResourceForEsReindex esReindex = new YxyResResourceForEsReindex();
                        esReindex.setResourceId(string);
                        yxyResResourceForEsReindexRepository.save(esReindex);
                    }
                }
            }
            List<ReqQuesModel> resQues = reqModel.resQues != null ? reqModel.resQues : new ArrayList<>();

            for (ReqQuesModel reqQuesModel : resQues) {
                String quesId = reqQuesModel.getId();
                Integer count = yxyResQuesRepository.countById(quesId);
                if (count == 0) {
                    YxyResQues ques = new YxyResQues();
                    ques.setId(quesId);
                    ques.setDifficultyLevel(reqQuesModel.getDifficultyLevel());
                    ques.setDifficultyXishu(reqQuesModel.getDifficultyXishu());
                    ques.setAbilityLevel(reqQuesModel.getAbilityLevel());
                    ques.setKnowledgeIds(reqQuesModel.getKnowledgeIds());
                    ques.setKnowFullIds(reqQuesModel.getKnowFullIds());
                    ques.setKnowledgeTexts(reqQuesModel.getKnowledgeTexts());
                    ques.setExamIds(reqQuesModel.getExamIds());
                    ques.setExamFullIds(reqQuesModel.getExamFullIds());
                    ques.setExamTexts(reqQuesModel.getExamTexts());
                    ques.setSrcAreaId(reqQuesModel.getSrcAreaId());
                    ques.setSrcYear(reqQuesModel.getSrcYear());
                    ques.setSrcAb(reqQuesModel.getSrcAb());
                    ques.setSrcType(reqQuesModel.getSrcType());
                    ques.setSrcName(reqQuesModel.getSrcName());
                    ques.setQuestionType(reqQuesModel.getQuestionType());
                    ques.setQuestionScore(reqQuesModel.getQuestionScore());
                    ques.setBody(reqQuesModel.getBody());
                    ques.setQuestionNo(reqQuesModel.getQuestionNo());
                    ques.setFlag(reqQuesModel.getFlag());
                    ques.setOldIds(reqQuesModel.getOldIds());
                    ques.setDocUrl(reqQuesModel.getDocUrl());
                    ques.setDeleteFlag(reqQuesModel.getDeleteFlag());
                    ques.setPhase(reqQuesModel.getPhase());
                    ques.setSubject(reqQuesModel.getSubject());
                    ques.setOid(reqQuesModel.getOid());
                    ques.setQuestionTime(reqQuesModel.getQuestionTime());
                    ques.setCreated(reqQuesModel.getCreated());
                    ques.setModified(reqQuesModel.getModified());
                    ques.setModifiedBy(reqQuesModel.getModifiedBy());
                    ques.setSycEsFlag(0);
                    ques.setViewScope(reqQuesModel.getViewScope());
                    ques.setHomeworkFavoriteCount(reqQuesModel.getHomeworkFavoriteCount());
                    ques.setHomeworkUseCount(reqQuesModel.getHomeworkUseCount());
                    yxyResQuesRepository.save(ques);
                }
            }
            // 备课资源
            List<ReqLectureResModel> lectureResModel = reqModel.lectureRes != null ? reqModel.lectureRes
                    : new ArrayList<>();
            for (ReqLectureResModel reqLectureResModel : lectureResModel) {
                YxyLectureRes yxyLectureRes = new YxyLectureRes();
                BeanUtils.copyProperties(reqLectureResModel, yxyLectureRes);
                Map<String, List<Knows>> quesKnowMap = new HashMap<String, List<Knows>>();
                List<ReqLectureResKnowModel> reqLectureResKnowModelList = reqModel.knowModels != null
                        ? reqModel.knowModels.stream()
                                .filter(x -> x.getResourceId().equals(yxyLectureRes.getResourceId()))
                                .collect(Collectors.toList())
                        : new ArrayList<>();
                for (ReqLectureResKnowModel reqLectureResKnowModel : reqLectureResKnowModelList) {
                    List<ReqLectureKnowModel> value = reqLectureResKnowModel.reqLectureKnowModelMap;
                    List<Knows> knows = new ArrayList<YxyLectureRes.Knows>();
                    for (ReqLectureKnowModel reqLectureKnowModel : value) {
                        Knows knows2 = new Knows();
                        knows2.know_id = reqLectureKnowModel.know_id;
                        knows2.know_name = reqLectureKnowModel.know_name;
                        knows.add(knows2);
                    }
                    quesKnowMap.put(reqLectureResKnowModel.getQuesId(), knows);
                }
                yxyLectureRes.setQuesKnows(quesKnowMap);
                yxyLectureResRepository.save(yxyLectureRes);
            }

            // 备课包
            ReqLecturePrePackModel reqLecturePrePackModel = reqModel.prePack;
            YxyLecturePrePack yxyLecturePrePack = new YxyLecturePrePack();
            BeanUtils.copyProperties(reqLecturePrePackModel, yxyLecturePrePack);
            if (reqLecturePrePackModel.getCreatedDate() != null) {
                Timestamp createdDate = new Timestamp(reqLecturePrePackModel.getCreatedDate().getTime());
                yxyLecturePrePack.setCreatedDate(createdDate);
            }
            yxyLecturePrePack.setIsSync(true);
            List<Res> preckres = new ArrayList<YxyLecturePrePack.Res>();
            List<ReqLecturePrePackResModel> preckResModels = reqModel.prePackRess.stream()
                    .filter(x -> x.getPackId().equals(reqLecturePrePackModel.getId())).collect(Collectors.toList());
            for (ReqLecturePrePackResModel reqLecturePrePackResModel : preckResModels) {
                Res res = yxyLecturePrePack.new Res();
                BeanUtils.copyProperties(reqLecturePrePackResModel, res);
                preckres.add(res);
            }
            yxyLecturePrePack.setResources(preckres);
            yxyLecturePrePackRepository.save(yxyLecturePrePack);

            resModel.success("成功");
        } catch (Exception e) {
            resModel.error(e.getMessage());
            LOGGER.error("同步备授课数据异常", e);
        }
        LOGGER.info("同步备授课数据结束");
        return resModel;
    }

}
